//
//  CJExten+Dict.swift
//  CJCore
//
//  Created by 陈警卫 on 2024-06-13.
//

import Foundation

public extension Dictionary {
    
    /// 字典Data
    func cj_data() -> Data? {
        let data = try? JSONSerialization.data(withJSONObject: self)
        return data
    }
    
    /// 字典转JSON字符串
    func cj_jsonString() -> String? {
        if (!JSONSerialization.isValidJSONObject(self)) {
            return nil
        }
        if let data = try? JSONSerialization.data(withJSONObject: self) {
            let jsonString = String(data: data, encoding: .utf8)
            return jsonString
        } else {
            return nil
        }
    }
    
    /// 判断包含某key
    func cj_has(_ key: Key) -> Bool {
        return index(forKey: key) != nil
    }
    
    /// 字典所有key
    func cj_allKeys() -> [Key] {
        // shuffled 返回新的随机化的数组
        return self.keys.shuffled()
    }
    
    /// 字典所有value
    func cj_allValues() -> [Value] {
        // shuffled 返回新的随机化的数组
        return self.values.shuffled()
    }
    
}

public extension Dictionary {
    
    /// 获取路径值
    func cj_pathValue(keys: [String]) -> Any? {
        guard let key = keys.first, let json = self as? [String: Any] else { return self }
        if let _ = json[key] as? [String: Any], keys.count > 1 {
            return cj_pathValue(keys: Array(keys.dropFirst()))
        } else if let value = json[key] {
            return value
        }
        return nil
    }
    
    /// 获取路径值
    func cj_pathValue<T>(keys: [String], t: T.Type) -> T? {
        let value = cj_pathValue(keys: keys)
        if let valuet = value as? T {
            return valuet
        }
        return nil
    }
    
    /// 获取路径值
    /// dafa: 默认值
    func cj_pathValue<T>(keys: [String], t: T.Type, defa: T) -> T {
        let value = cj_pathValue(keys: keys)
        if let valuet = value as? T {
            return valuet
        }
        return defa
    }
}

public extension Dictionary {
    
    /// JSON字符串转字典
    static func cj_dictionary(_ jsonString: String) -> Dictionary? {
        guard let data = jsonString.data(using: .utf8) else {
            return nil
        }
        if let dict = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? Dictionary {
            return dict
        }
        return nil
    }
}
